import logging
import os
from datetime import datetime, timedelta

from flask import Blueprint, jsonify, request
from app.config.paths import SMT2_REFLOW_PATH

smt2_reflow_soldering_bp = Blueprint('smt2_reflow_soldering', __name__)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 定义SMT2回流焊数据文件的路径
# SMT2_REFLOW_PATH = "/mnt/smt2/reflow_soldering/"


@smt2_reflow_soldering_bp.route('/api/smt2/reflow_soldering/temperature_curve', methods=['GET'])
def get_reflow_temperature_curve():
    """获取SMT2回流焊最近一段时间的温度曲线数据"""
    try:
        logger.info("查询SMT2回流焊温度曲线数据")

        # 获取查询参数
        hours = request.args.get('hours', 24, type=int)  # 默认获取最近24小时
        start_time = request.args.get('start_time', None)  # 可选起始时间
        end_time = request.args.get('end_time', None)  # 可选结束时间
        limit = request.args.get('limit', 50, type=int)  # 限制返回的记录数

        # 检查目录是否存在
        if not os.path.exists(SMT2_REFLOW_PATH):
            return jsonify({
                "success": False,
                "message": f"回流焊数据目录不存在: {SMT2_REFLOW_PATH}"
            }), 404

        # 获取目录中所有txt文件
        txt_files = [os.path.join(SMT2_REFLOW_PATH, f) for f in os.listdir(SMT2_REFLOW_PATH)
                     if f.endswith('.txt') and os.path.isfile(os.path.join(SMT2_REFLOW_PATH, f))]

        if not txt_files:
            return jsonify({
                "success": False,
                "message": "未找到任何回流焊数据文件"
            }), 404

        # 解析文件名中的时间信息或使用文件修改时间
        file_data = []

        for file_path in txt_files:
            file_name = os.path.basename(file_path)

            # 尝试从文件名解析时间 (格式为 "YYYY-MM-DD HH-MM-SS.txt")
            try:
                file_time_str = os.path.splitext(file_name)[0]
                file_time = datetime.strptime(file_time_str, "%Y-%m-%d %H-%M-%S")
            except:
                # 如果无法从文件名解析，使用文件修改时间
                file_time = datetime.fromtimestamp(os.path.getmtime(file_path))

            file_data.append({
                "file_path": file_path,
                "timestamp": file_time
            })

        # 根据时间筛选文件
        now = datetime.now()

        if start_time and end_time:
            # 如果提供了具体的开始和结束时间
            start_dt = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
            end_dt = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")

            filtered_files = [f for f in file_data if start_dt <= f["timestamp"] <= end_dt]
        else:
            # 否则获取最近几个小时的数据
            time_threshold = now - timedelta(hours=hours)
            filtered_files = [f for f in file_data if f["timestamp"] >= time_threshold]

        # 按时间排序
        filtered_files.sort(key=lambda x: x["timestamp"])

        # 限制返回数量
        if len(filtered_files) > limit:
            filtered_files = filtered_files[-limit:]

        # 解析文件内容，提取温度数据
        temperature_data = []

        for file_info in filtered_files:
            try:
                # 首先尝试UTF-8编码
                try:
                    with open(file_info["file_path"], 'r', encoding='utf-8') as file:
                        content = file.read()
                except UnicodeDecodeError:
                    # 如果UTF-8失败，尝试GBK编码（常见于中文Windows系统）
                    with open(file_info["file_path"], 'r', encoding='gbk') as file:
                        content = file.read()

                # 解析文件内容
                timestamp = None
                temp_up_set = []
                temp_down_set = []
                temp_up_actual = []
                temp_down_actual = []
                fan_speeds = []
                chain_speed_set = None
                chain_speed_actual = None
                oxygen_level = None

                for line in content.splitlines():
                    line = line.strip()
                    if line.startswith("时间:"):
                        timestamp = line.replace("时间:", "").strip()
                    elif line.startswith("温度设定上:"):
                        values = line.replace("温度设定上:", "").strip().split()
                        temp_up_set = [int(t) if t.isdigit() else 0 for t in values]
                    elif line.startswith("温度设定下:"):
                        values = line.replace("温度设定下:", "").strip().split()
                        temp_down_set = [int(t) if t.isdigit() else 0 for t in values]
                    elif line.startswith("实际温度上:"):
                        values = line.replace("实际温度上:", "").strip().split()
                        temp_up_actual = [int(t) if t.isdigit() else 0 for t in values]
                    elif line.startswith("实际温度下:"):
                        values = line.replace("实际温度下:", "").strip().split()
                        temp_down_actual = [int(t) if t.isdigit() else 0 for t in values]
                    elif line.startswith("风机"):
                        parts = line.split(":")
                        if len(parts) == 2:
                            try:
                                fan_speeds.append(int(parts[1].strip()))
                            except ValueError:
                                fan_speeds.append(0)
                    elif line.startswith("链速设定:"):
                        try:
                            chain_speed_set = int(line.replace("链速设定:", "").strip())
                        except ValueError:
                            chain_speed_set = 0
                    elif line.startswith("链速实际:"):
                        try:
                            chain_speed_actual = int(line.replace("链速实际:", "").strip())
                        except ValueError:
                            chain_speed_actual = 0
                    elif line.startswith("氧气浓度:"):
                        oxygen_level = line.replace("氧气浓度:", "").strip()

                temperature_data.append({
                    "timestamp": timestamp,
                    "file_time": file_info["timestamp"].strftime("%Y-%m-%d %H:%M:%S"),
                    "temperature_set_up": temp_up_set,
                    "temperature_set_down": temp_down_set,
                    "temperature_actual_up": temp_up_actual,
                    "temperature_actual_down": temp_down_actual,
                    "fan_speeds": fan_speeds,
                    "chain_speed_set": chain_speed_set,
                    "chain_speed_actual": chain_speed_actual,
                    "oxygen_level": oxygen_level
                })
            except Exception as e:
                logger.warning(f"解析文件 {file_info['file_path']} 失败: {str(e)}")
                continue  # 跳过此文件，继续处理其他文件

        # 准备前端图表所需的格式化数据
        chart_data = {
            "timestamps": [item["timestamp"] for item in temperature_data],
            "temperature_curves": {
                "温度设定上": [item["temperature_set_up"] for item in temperature_data],
                "温度设定下": [item["temperature_set_down"] for item in temperature_data],
                "实际温度上": [item["temperature_actual_up"] for item in temperature_data],
                "实际温度下": [item["temperature_actual_down"] for item in temperature_data]
            },
            "fan_speeds": [item["fan_speeds"] for item in temperature_data],
            "chain_speeds": {
                "设定": [item["chain_speed_set"] for item in temperature_data],
                "实际": [item["chain_speed_actual"] for item in temperature_data]
            }
        }

        return jsonify({
            "success": True,
            "raw_data": temperature_data,
            "chart_data": chart_data,
            "count": len(temperature_data),
            "query_params": {
                "hours": hours if not (start_time and end_time) else None,
                "start_time": start_time,
                "end_time": end_time,
                "limit": limit
            }
        })

    except Exception as e:
        logger.error(f"查询SMT2回流焊温度曲线数据失败: {str(e)}")
        return jsonify({
            "success": False,
            "message": f"查询失败: {str(e)}"
        }), 500
